﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Hisun.Models;

namespace Hisun.View.SCRB
{
    public partial class Scrb_daily_newInput : System.Web.UI.Page
    {
        private string mypipID;
        int mycostcenterID;
        DateTime dt_myday;
        public string alter;

        HisunDBDataContext db = new HisunDBDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            mypipID = HttpUtility.UrlDecode(Request.QueryString["mypip"]);
            dt_myday = DateTime.Parse(HttpUtility.UrlDecode(Request.QueryString["myday"]));
            bindmypip();

            if (!IsPostBack)
            {

                BindEmptyData();
            }
        }
        /// <summary>
        /// 获取当前会计期间
        /// </summary>
        /// <param name="it_date"></param>
        /// <returns></returns>
        private string getAccoutperiod(DateTime it_date)
        {

            var kjqk = (from a in db.TABC_JS_AccountPeriod
                        where a.成本开始日期 <= it_date
                               && a.成本结账日期 >= it_date
                        select a.会计期间ID).Single();

            return kjqk;
        }
        private string getAccoutperiod()
        {
            return getAccoutperiod(this.dt_myday);
        }

        private void bindmypip()
        {
            var mypip = (from a in db.TABC_JS_ProductInProcess
                         where a.中间体ID == mypipID
                         select a).Single();


            mycostcenterID = (int)mypip.作业中心ID;
            string mycostcentername = (from a in db.TABC_JS_CostCenter
                                       where a.作业中心ID == mycostcenterID
                                       select a.作业中心名称).Single();

            Label_CostCenter.Text = mycostcentername;
            Label_PIPNAME.Text = mypip.中间体名称;
            Label_myday.Text = dt_myday.ToShortDateString();



        }

        private string splitbatch(string batch)
        {
            if (batch.IndexOf('/') > 0)
            {
                batch = batch.Split('/')[1];
            }

            return batch;
        }

        private string joinbatch(string batch)
        {
            if (batch.IndexOf('/') > 0)
            {
                return batch;
            }
            return this.mypipID + "/" + batch;

        }

        

        protected void BindEmptyData()
        {
            DataTable dt1 = new DataTable();
            dt1.Columns.Add("ID");
            dt1.Columns.Add("批号");
            dt1.Columns.Add("折批系数");
            dt1.Columns.Add("批时");
            dt1.Columns.Add("允许删除",typeof(bool)); 

            var qs = from a in db.TSCRB_JS_BatchInfo
                     join b in db.TSCRB_JS_BatchInfoDetail
                     on a.批号 equals b.批号
                     where a.中间体ID == mypipID 
                     && b.投入日期 == dt_myday  
                     && a.批号类型 == "N"
                     select new
                     {
                         a.ID,
                         a.批号,
                         a.折批系数,
                         a.批时
                     };
            foreach (var q in qs)
            {
                dt1.Rows.Add(new object[] { q.ID, splitbatch(q.批号), q.折批系数, q.批时,true });
            }

            for (int i = 0; i <= 4; i++)
            {
                dt1.Rows.Add(new object[] { 0, "", 1, "" ,false});
            }
            dt1.AcceptChanges();
            GridView1.DataSource = dt1;
            GridView1.DataBind();

        }
        protected DataTable GetDataFromGrid()
        {

            DataTable dt1 = new DataTable();
            dt1.Columns.Add("ID");
            dt1.Columns.Add("批号");
            dt1.Columns.Add("折批系数");
            dt1.Columns.Add("批时");
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridViewRow gRow = GridView1.Rows[i];
                DataRow newRow = dt1.NewRow();
                newRow[0] = GridView1.DataKeys[i].Value;
                newRow[1] = ((TextBox)gRow.FindControl("TextBox1")).Text;
                newRow[2] = ((TextBox)gRow.FindControl("TextBox2")).Text;
                newRow[3] = ((TextBox)gRow.FindControl("TextBox3")).Text;
                dt1.Rows.Add(newRow);
            }
            dt1.AcceptChanges();
            return dt1;
        }


        private bool checkbachexist(string batchnumber)
        {
            if (batchnumber.IndexOf('/') < 0)
            {
                batchnumber = joinbatch(batchnumber);
            }
            var q = from a in db.TSCRB_JS_BatchInfo
                    where
                        a.批号 == batchnumber
                    select a;
            if (q.Count() > 0)
            {
                return true;
            }
            return false;

        }
        protected void Button_Save_Click(object sender, EventArgs e)
        {   
              string ErrorBacthNumber = "";

            DataTable dt1 = GetDataFromGrid();

            double 折批系数, 批时;
            try
            {
                foreach (DataRow row in dt1.Rows)
                {
                    if (row["ID"].ToString() != "0")
                    {
                        if (row["批号"].ToString().Length > 1)
                        {
                            if (checkbachexist(row["批号"].ToString()))
                            {
                                // Label_alter.Text += row["批号"].ToString() + "批号重复,";

                                var update = (from a in db.TSCRB_JS_BatchInfo
                                              where a.ID == long.Parse(row["ID"].ToString())
                                              select a).Single();
                                折批系数 = 1;
                                批时 = 0;
                                double.TryParse(row["折批系数"].ToString(), out 折批系数);
                                double.TryParse(row["批时"].ToString(), out  批时);
                                update.批时 = 批时;
                                update.折批系数 = 折批系数;
                                db.SubmitChanges();

                            }
                            else
                            {
                                var update = (from a in db.TSCRB_JS_BatchInfo
                                              where a.ID == long.Parse(row["ID"].ToString())
                                              select a).Single();
                                var updatedetail = (from a in db.TSCRB_JS_BatchInfoDetail
                                                    where a.批号 == update.批号
                                                    select a).Single();
                                update.批号 = joinbatch(row["批号"].ToString());
                                updatedetail.批号 = joinbatch(row["批号"].ToString());

                                折批系数 = 1;
                                批时 = 0;
                                double.TryParse(row["折批系数"].ToString(), out 折批系数);
                                double.TryParse(row["批时"].ToString(), out  批时);
                                update.批时 = 批时;
                                update.折批系数 = 折批系数;
                                db.SubmitChanges();
                            }
                        }
                    }
                    else
                    {//插入
                        if (row["批号"].ToString().Length > 1)
                        {
                            if (checkbachexist(row["批号"].ToString()))
                            {
                                ErrorBacthNumber += row["批号"].ToString() + ",";

                                Label_alter.Text += row["批号"].ToString() + "批号重复,";
                            }
                            else
                            {

                                //插入批号信息表
                                TSCRB_JS_BatchInfo batchinfo = new TSCRB_JS_BatchInfo();
                                batchinfo.会计期间ID = this.getAccoutperiod();
                                batchinfo.中间体ID = this.mypipID;
                                batchinfo.批号类型 = "N";
                                //   batchinfo.状态 = "K";
                                折批系数 = 1;
                                批时 = 0;
                                double.TryParse(row["折批系数"].ToString(), out 折批系数);
                                batchinfo.折批系数 = 折批系数;
                                batchinfo.批号 = joinbatch(row["批号"].ToString());
                                double.TryParse(row["批时"].ToString(), out  批时);
                                batchinfo.批时 = 批时;
                                db.TSCRB_JS_BatchInfo.InsertOnSubmit(batchinfo);

                                //插入detail表
                                TSCRB_JS_BatchInfoDetail batchinfodetail = new TSCRB_JS_BatchInfoDetail();
                                batchinfodetail.会计期间ID = batchinfo.会计期间ID;
                                batchinfodetail.批号 = batchinfo.批号;
                                batchinfodetail.投入日期 = dt_myday;
                                batchinfodetail.中间体ID = batchinfo.中间体ID;
                                db.TSCRB_JS_BatchInfoDetail.InsertOnSubmit(batchinfodetail);

                                db.SubmitChanges();

                            }
                        }


                    }


                }
                if (ErrorBacthNumber == "")
                {
                    alter = "<script>alert('保存成功');</script>";
                }
                else
                {
                    alter = "<script>alert('完成操作,但" + ErrorBacthNumber + "等批号重复,只保存一条记录'"+");</script>";
                }

                 BindEmptyData();
            }
            catch
            {
                alter = "<script>alert('保存失败');</script>";
            
            }


          
        }

        protected void Button_Back_Click(object sender, EventArgs e)
        {
            Response.Redirect("Scrb_Daily_MainPage.aspx?centerid=" + mycostcenterID.ToString() + "&PIPid=" + mypipID);
        }

        protected void DelBatch(object sender, CommandEventArgs e)
        {
            long ID = 0;

            try
            {
                ID = long.Parse(e.CommandArgument.ToString());
            }
            catch
            {
            }
            if (ID > 0)
            {
                try
                {
                    var q = from a in db.TSCRB_JS_BatchInfo
                            where a.ID == ID
                            select a.批号;
                    string MyDelString = q.Single().ToString();
                    Batch del = new Batch();
                    if (del.DelBatch(q.Single()))
                    {
                        //Label_alter.Text = "删除" + q.Single() + "成功";
                        alter = "<script>alert('删除" + MyDelString + "成功'" + ");</script>";
                    }


                }
                catch
                {
                }

                

            }

            BindEmptyData();



        }
    }
}
